#    Copyright 2011 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPIP.
#    COOPIP is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPIP is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPIP.  If not, see <http://www.gnu.org/licenses/>.

import os
import datetime
import shutil

#************************BEGIN Add Include Files to Path************************
import sys
NeededPaths=['/opt/coopip/djangoproject/include', '/opt/coopip/djangoproject']
for path in NeededPaths:
    if(not path in sys.path):
        sys.path.append(path)
#************************END   Add Include Files to Path************************
from django.contrib.gis.geos import *
import os, time, psycopg2, datetime
#********************Setup psycopg2 and django section********************
PathDjangoRoot="/opt/coopip/"
if(not PathDjangoRoot in sys.path):
    sys.path.append(PathDjangoRoot)
from django.core.management import setup_environ
import djangoproject
from djangoproject import settings
setup_environ(settings)
from models import *
#********************Setup psycopg2 and django section********************

from django.template import Context, loader
from django.http import HttpResponse
from django import forms
import os
import datetime
import djangoproject.settings
import COOPIP_Misc, COOPIP_Form, COOPIP_Authentication
import djangoproject.models.revenueprotection
from djangoproject.models.ipbase import *
from django.contrib.gis.geos import *
import AMR, GIS

def BuildIncidentForm(SpecialBuildFormDataDict):
    Dict={}
    try:
        Incident = SpecialBuildFormDataDict['Incident']
    except:
        Incident=None

    #Only Admins may view/edit InProgress or Closed Incidents, so if an incident was selected, check here.
    Permission, LoginStatus, Username = COOPIP_Authentication.COOPIPAuthenticate(SpecialBuildFormDataDict['request'], ['COOPIP_RevenueProtectionAdmin'], True)
    SelectIncidentChoices=[]
    if(Incident):
        SelectIncidentChoices.append([Incident.id, str(Incident)])
    SelectIncidentChoices.append([-1, 'None Selected'])
    if(Permission):
        Incidents=djangoproject.models.revenueprotection.Incident.objects.all().order_by('id')
    else:
        Incidents=djangoproject.models.revenueprotection.Incident.objects.all().exclude(ClosedIndicator=True).exclude(InProgressIndicator=True).order_by('id')
    for incident in Incidents:
        if(not [incident.id, str(incident)] in SelectIncidentChoices):
            SelectIncidentChoices.append([incident.id, str(incident)])

    CountyChoices=[]
    Dict['SelectIncident']=forms.ChoiceField(SelectIncidentChoices, required=False)
    Dict['UpdateIndicator']=forms.BooleanField(required=False)
    Dict['NewIndicator']=forms.BooleanField(required=False)
    Dict['Incidentid']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'5', 'READONLY':'True'}))
    Dict['InitialFindingsIndicator']=forms.BooleanField(required=False)
    Dict['InitialFindingsDescription']=forms.CharField(required=False, widget=forms.Textarea(attrs={'rows':'2', 'cols':'40'}))
    Dict['InitialFindingsDateTime']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'6.5', 'READONLY':'True'}))
    Dict['FilmIndicator']=forms.BooleanField(required=False)
    Dict['FilmUploadedIndicator']=forms.BooleanField(required=False)
    Dict['InProgressIndicator']=forms.BooleanField(required=False)
    Dict['InProgressDescription']=forms.CharField(required=False, widget=forms.Textarea(attrs={'rows':'2', 'cols':'40'}))
    Dict['InProgressDateTime']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'6.5', 'READONLY':'True'}))
    Dict['ClosedIndicator']=forms.BooleanField(required=False)
    Dict['ClosedDescription']=forms.CharField(required=False, widget=forms.Textarea(attrs={'rows':'2', 'cols':'40'}))
    Dict['ClosedDateTime']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'6.5', 'READONLY':'True'}))
    Dict['CutSealIndicator']=forms.BooleanField(required=False)
    Dict['MeterProperPositionIndicator']=forms.BooleanField(required=False)
    Dict['MeterConditionDescription']=forms.CharField(required=False, widget=forms.Textarea(attrs={'rows':'2', 'cols':'40'}))
    Dict['MeterSealInPlaceIndicator']=forms.BooleanField(required=False)
    Dict['JumperIndicator']= forms.BooleanField(required=False)
    Dict['MeterBaseGoodConditionIndicator']=forms.BooleanField(required=False)
    Dict['LockGoodConditionIndicator']=forms.BooleanField(required=False)
    Dict['DateTime']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'15'}))
    Dict['DateTimeSetToNowIndicator']=forms.BooleanField(required=False)
    Dict['MapNumber']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'15'}))
    Dict['NameOnAccount']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'15'}))
    Dict['VehicleTagNumber']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'15'}))
    Dict['VehicleDescription']=forms.CharField(required=False, widget=forms.Textarea(attrs={'rows':'2', 'cols':'40'}))
    Dict['CutSealCharge']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'5'}))
    Dict['TamperCharge']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'5'}))
    Dict['ServiceCharge']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'5'}))
    Dict['VehiclesAtLocation']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'15'}))
    Dict['MiscellaneousCharge']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'5'}))
    Dict['ChargeDescription']=forms.CharField(required=False, widget=forms.Textarea(attrs={'rows':'2', 'cols':'40'}))
    Dict['StolenCurrentCharge']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'5'}))
    Dict['TotalTheftCharges']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'5'}))
    Dict['CaseNumber']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'15'}))
    Dict['County']=forms.ChoiceField(CountyChoices, required=False)
    Dict['WarrantRequestedIndicator']=forms.BooleanField(required=False)
    Dict['PastDueBillAmount']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'5'}))
    Dict['BadDebtAmount']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'5'}))
    Dict['HearingDateTime']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'15'}))
    Dict['Decision']=forms.CharField(required=False, widget=forms.Textarea(attrs={'rows':'2', 'cols':'40'}))
    Dict['OrderRestitutionIndicator']=forms.BooleanField(required=False)
    Dict['AccountName']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'15'}))
    Dict['AddressOne']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'15'}))
    Dict['AddressTwo']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'15'}))
    Dict['AddressThree']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'15'}))
    Dict['City']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'5'}))
    Dict['State']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'1'}))
    Dict['Zip']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'5'}))
    Dict['HomePhone']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'15'}))
    Dict['CellPhone']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'15'}))
    Dict['OtherPhone']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'15'}))
    Dict['Fax']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'15'}))
    Dict['Email']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'15'}))
    Dict['FilmIndicator']=forms.BooleanField(required=False)
    Dict['FilmUploadedIndicator']=forms.BooleanField(required=False)
    Dict['EvidenceBagNumber']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'15'}))
    Dict['Note']=forms.CharField(required=False, widget=forms.Textarea(attrs={'rows':'2', 'cols':'40'}))
    Dict['UploadFile']=forms.FileField()

    Dict['Longitude']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'5'}))
    Dict['Latitude']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'5'}))
    Dict['UpdatePointManuallyIndicator']=forms.BooleanField(required=False)
    Dict['UpdatePointFromGISIndicator']=forms.BooleanField(required=False)
    Dict['UpdatePointFromGISField']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'5'}))

    Dict['LegalCodeTheftIndicator']=forms.BooleanField(required=False)
    Dict['LegalCodeAlterIndicator']=forms.BooleanField(required=False)
    Dict['LegalCodeCheatIndicator']=forms.BooleanField(required=False)

    Dict['NewPaymentIndicator']=forms.BooleanField(required=False)
    Dict['NewPaymentAmount']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'5'}))
    Dict['NewPaymentDateTime']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'15'}))
    Dict['NewPaymentDescription']=forms.CharField(required=False, widget=forms.Textarea(attrs={'rows':'2', 'cols':'40'}))
    Dict['Description']=forms.CharField(required=False, widget=forms.Textarea(attrs={'rows':'2', 'cols':'40'}))
    Dict['DeleteFile']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'15'}))
    Dict['DeleteFileIndicator']=forms.BooleanField(required=False)
    return Dict

def ProcessIncidentForm(form, Username, request):
    SelectIncidentid=COOPIP_Form.FormGetInteger(form, 'SelectIncident')
    UpdateIndicator=COOPIP_Form.FormGetBoolean(form, 'UpdateIndicator')
    NewIndicator=COOPIP_Form.FormGetBoolean(form, 'NewIndicator')
    if(NewIndicator):
        SelectedIncident=djangoproject.models.revenueprotection.Incident()
    elif(not SelectIncidentid == -1 and SelectIncidentid):
        SelectedIncident=djangoproject.models.revenueprotection.Incident.objects.filter(id=SelectIncidentid)[0]
    else:
        return #If no incident selected, cannot process changes to an incident with this form

    #Only Admins may view/edit InProgress or Closed Incidents, so if an incident was selected, check here.
    if(SelectedIncident and (SelectedIncident.InProgressIndicator or SelectedIncident.ClosedIndicator)):
        Permission, LoginStatus, Username = COOPIP_Authentication.COOPIPAuthenticate(request, ['COOPIP_RevenueProtectionAdmin'], True)
        if(not Permission):
            return
    try:
        UploadFile=request.FILES['UploadFile']
    except:
        UploadFile=None

    if(NewIndicator or UpdateIndicator):
        if(NewIndicator):
            SelectedIncident.InitialFindingsDateTime=datetime.datetime.now()
            SelectedIncident.InitialFindingsIndicator=True
        else:
            SelectedIncident.InitialFindingsIndicator=COOPIP_Form.FormGetBoolean(form, 'InitialFindingsIndicator')
        SelectedIncident.InitialFindingsDescription=COOPIP_Form.FormGetString(form, 'InitialFindingsDescription')
        if(not SelectedIncident.InProgressIndicator and COOPIP_Form.FormGetBoolean(form, 'InProgressIndicator')):
            SelectedIncident.InProgressDateTime=datetime.datetime.now()
        SelectedIncident.InProgressIndicator=COOPIP_Form.FormGetBoolean(form, 'InProgressIndicator')
        SelectedIncident.InProgressDescription=COOPIP_Form.FormGetString(form, 'InProgressDescription')
        SelectedIncident.Description=COOPIP_Form.FormGetString(form, 'Description')

        if(not SelectedIncident.ClosedIndicator and COOPIP_Form.FormGetBoolean(form, 'ClosedIndicator')):
            SelectedIncident.ClosedDateTime=datetime.datetime.now()
        SelectedIncident.ClosedIndicator=COOPIP_Form.FormGetBoolean(form, 'ClosedIndicator')
        SelectedIncident.ClosedDescription=COOPIP_Form.FormGetString(form, 'ClosedDescription')

        SelectedIncident.CutSealIndicator=COOPIP_Form.FormGetBoolean(form, 'CutSealIndicator')
        SelectedIncident.MeterProperPositionIndicator=COOPIP_Form.FormGetBoolean(form, 'MeterProperPositionIndicator')
        SelectedIncident.MeterConditionDescription=COOPIP_Form.FormGetString(form, 'MeterConditionDescription')
        SelectedIncident.MeterSealInPlaceIndicator=COOPIP_Form.FormGetBoolean(form, 'MeterSealInPlaceIndicator')
        SelectedIncident.JumperIndicator=COOPIP_Form.FormGetBoolean(form, 'JumperIndicator')
        SelectedIncident.MeterBaseGoodConditionIndicator=COOPIP_Form.FormGetBoolean(form, 'MeterBaseGoodConditionIndicator')
        SelectedIncident.LockGoodConditionIndicator=COOPIP_Form.FormGetBoolean(form, 'LockGoodConditionIndicator')
        SelectedIncident.DateTimeSetToNowIndicator=COOPIP_Form.FormGetBoolean(form, 'DateTimeSetToNowIndicator')
        SelectedIncident.MapNumber=COOPIP_Form.FormGetString(form, 'MapNumber')
        SelectedIncident.NameOnAccount=COOPIP_Form.FormGetString(form, 'NameOnAccount')
        SelectedIncident.VehicleTagNumber=COOPIP_Form.FormGetString(form, 'VehicleTagNumber')
        SelectedIncident.VehicleDescription=COOPIP_Form.FormGetString(form, 'VehicleDescription')
        SelectedIncident.CutSealCharge=COOPIP_Form.FormGetFloat(form, 'CutSealCharge')
        SelectedIncident.TamperCharge=COOPIP_Form.FormGetFloat(form, 'TamperCharge')
        SelectedIncident.ServiceCharge=COOPIP_Form.FormGetFloat(form, 'ServiceCharge')
        SelectedIncident.VehiclesAtLocation=COOPIP_Form.FormGetString(form, 'VehiclesAtLocation')
        SelectedIncident.MiscellaneousCharge=COOPIP_Form.FormGetFloat(form, 'MiscellaneousCharge')
        SelectedIncident.ChargeDescription=COOPIP_Form.FormGetString(form, 'ChargeDescription')
        SelectedIncident.StolenCurrentCharge=COOPIP_Form.FormGetFloat(form, 'StolenCurrentCharge')
        SelectedIncident.TotalTheftCharges=COOPIP_Form.FormGetFloat(form, 'TotalTheftCharges')
        SelectedIncident.CaseNumber=COOPIP_Form.FormGetString(form, 'CaseNumber')
        SelectedIncident.County=COOPIP_Form.FormGetObjectFromid(form, 'Countyid', djangoproject.models.revenueprotection.County)
        SelectedIncident.WarrantRequestedIndicator=COOPIP_Form.FormGetBoolean(form, 'WarrantRequestedIndicator')
        SelectedIncident.PastDueBillAmount=COOPIP_Form.FormGetFloat(form, 'PastDueBillAmount')
        SelectedIncident.BadDebtAmount=COOPIP_Form.FormGetFloat(form, 'BadDebtAmount')
        SelectedIncident.HearingDateTime=COOPIP_Form.FormGetDateTime(form, 'HearingDateTime')
        SelectedIncident.Decision=COOPIP_Form.FormGetString(form, 'Decision')
        SelectedIncident.OrderRestitutionIndicator=COOPIP_Form.FormGetBoolean(form, 'OrderRestitutionIndicator')
        SelectedIncident.AccountName=COOPIP_Form.FormGetString(form, 'AccountName')
        SelectedIncident.AddressOne=COOPIP_Form.FormGetString(form, 'AddressOne')
        SelectedIncident.AddressTwo=COOPIP_Form.FormGetString(form, 'AddressTwo')
        SelectedIncident.AddressThree=COOPIP_Form.FormGetString(form, 'AddressThree')
        SelectedIncident.State=COOPIP_Form.FormGetString(form, 'State')
        SelectedIncident.Zip=COOPIP_Form.FormGetString(form, 'Zip')
        SelectedIncident.omePhone=COOPIP_Form.FormGetString(form, 'HomePhone')
        SelectedIncident.CellPhone=COOPIP_Form.FormGetString(form, 'CellPhone')
        SelectedIncident.OtherPhone=COOPIP_Form.FormGetString(form, 'OtherPhone')
        SelectedIncident.Fax=COOPIP_Form.FormGetString(form, 'Fax')
        SelectedIncident.Email=COOPIP_Form.FormGetString(form, 'Email')
        SelectedIncident.FilmIndicator=COOPIP_Form.FormGetBoolean(form, 'FilmIndicator')
        SelectedIncident.FilmUploadedIndicator=COOPIP_Form.FormGetBoolean(form, 'FilmUploadedIndicator')
        SelectedIncident.EvidenceBagNumber=COOPIP_Form.FormGetString(form, 'EvidenceBagNumber')
        SelectedIncident.LegalCodeTheftIndicator=COOPIP_Form.FormGetBoolean(form, 'LegalCodeTheftIndicator')
        SelectedIncident.LegalCodeAlterIndicator=COOPIP_Form.FormGetBoolean(form, 'LegalCodeAlterIndicator')
        SelectedIncident.LegalCodeCheatIndicator=COOPIP_Form.FormGetBoolean(form, 'LegalCodeCheatIndicator')
        if(COOPIP_Form.FormGetBoolean(form, 'UpdatePointFromGISIndicator')):
            UpdatePointFromGISField=COOPIP_Form.FormGetInteger(form, 'UpdatePointFromGISField')
            Latitude=None
            Longitude=None
            point = None

            if(GIS.Coopgisassembly.objects.filter(meterdcsinumber=UpdatePointFromGISField).count() == 1):
                try:
                    point=GIS.Coopgisassembly.objects.filter(meterdcsinumber=UpdatePointFromGISField)[0].station.the_geom
                except:
                    pass
            elif(GIS.Assembly.objects.filter(oldmapnumber=UpdatePointFromGISField).count() == 1):
                try:
                    point=GIS.Coopgisassembly.objects.filter(oldmapnumber=UpdatePointFromGISField)[0].station.the_geom
                except IOError:
                    pass
            elif(GIS.Coopgisstation.objects.filter(id=UpdatePointFromGISField)):
                try:
                    point = GIS.Coopgisstation.objects.filter(id=UpdatePointFromGISField)[0].the_geom
                except:
                    pass
            if(point):
                SelectedIncident.Point=point.transform(djangoproject.settings.COOPIPGPSSRID, clone=True)
        elif(COOPIP_Form.FormGetBoolean(form, 'UpdatePointManuallyIndicator')):
            Longitude=COOPIP_Form.FormGetFloat(form, 'Longitude')
            Latitude=COOPIP_Form.FormGetFloat(form, 'Latitude')
            point=Point(Longitude, Latitude, srid=djangoproject.settings.COOPIPGPSSRID)
            #raise(Exception(str(point)))
            SelectedIncident.Point=point


        SelectedIncident.save()
        if(SelectedIncident and COOPIP_Form.FormGetBoolean(form, 'NewPaymentIndicator')):
            NewPayment=djangoproject.models.revenueprotection.IncidentPayment()
            NewPayment.Amount=COOPIP_Form.FormGetFloat(form, 'NewPaymentAmount')
            NewPayment.DateTime=COOPIP_Form.FormGetDateTime(form, 'NewPaymentDateTime')
            NewPayment.Description=COOPIP_Form.FormGetString(form, 'NewPaymentDescription')
            NewPayment.Incident=SelectedIncident
            if(not NewPayment.DateTime):
                NewPayment.DateTime=datetime.datetime.now()
            NewPayment.save()


    if(SelectedIncident and UploadFile and UpdateIndicator):   #Process File Uploading
        BaseFileName=str(UploadFile).split('.')[0]
        Extension=str(UploadFile).split('.')[-1]
        FileName=str(BaseFileName + '.' + Extension)
        try:
            incidentFile=djangoproject.models.revenueprotection.IncidentFile.objects.filter(Incident=SelectedIncident).filter(FileName=FileName)[0]
        except:
            incidentFile=djangoproject.models.revenueprotection.IncidentFile()
            incidentFile.FileName=FileName
            incidentFile.Incident=SelectedIncident
            incidentFile.save()
        incidentFile.File=str(incidentFile.id)
        destination=open(djangoproject.settings.MEDIA_ROOT + 'incident/' + str(incidentFile.id), 'wb+')
        for chunk in UploadFile.chunks():
            destination.write(chunk)
        destination.close()
        incidentFile.DateTime=datetime.datetime.now()
        incidentFile.save()
    DeleteFile=COOPIP_Form.FormGetString(form, 'DeleteFile')
    DeleteFileIndicator=COOPIP_Form.FormGetBoolean(form, 'DeleteFileIndicator')
    if(SelectedIncident and DeleteFileIndicator and DeleteFile and UpdateIndicator):
        try:
            incidentFile=djangoproject.models.intranet.IncidentFile.objects.filter(Incident=SelectedIncident).filter(FileName=DeleteFile)[0]
            os.remove(djangoproject.settings.MEDIA_ROOT + 'incident/' + str(incidentFile.id))
            incidentFile.delete()
        except:
            pass


    Note=COOPIP_Form.FormGetString(form, 'Note')
    if(SelectedIncident and Note):
        NewIncidentNote=djangoproject.models.revenueprotection.IncidentNote()
        NewIncidentNote.Incident=SelectedIncident
        NewIncidentNote.Description=Note
        NewIncidentNote.Username=Username
        NewIncidentNote.DateTime=datetime.datetime.now()
        NewIncidentNote.save()
    return SelectedIncident

def PopulateIncidentForm(form, incident):
    form.data['UpdateIndicator']=False
    form.data['NewIndicator']=False
    form.data['UploadFile']=''
    form.data['Note']=''
    form.data['DateTimeSetToNowIndicator']=False
    form.data['DeleteFile']=''
    form.data['DeleteFileIndicator']=False

    if(incident):
        form.data['SelectIncident']=incident.id
        form.data['Incidentid']=incident.id
        form.data['InitialFindingsIndicator']=incident.InitialFindingsIndicator
        form.data['InitialFindingsDescription']=incident.InitialFindingsDescription
        form.data['InitialFindingsDateTime']=incident.InitialFindingsDateTime
        form.data['FilmIndicator']=incident.FilmIndicator
        form.data['FilmUploadedIndicator']=incident.FilmUploadedIndicator
        form.data['InProgressIndicator']=incident.InProgressIndicator
        form.data['InProgressDescription']=incident.InProgressDescription
        form.data['InProgressDateTime']=incident.InProgressDateTime
        form.data['ClosedIndicator']=incident.ClosedIndicator
        form.data['ClosedDescription']=incident.ClosedDescription
        form.data['ClosedDateTime']=incident.ClosedDateTime
        form.data['CutSealIndicator']=incident.CutSealIndicator
        form.data['MeterProperPositionIndicator']=incident.MeterProperPositionIndicator
        form.data['MeterConditionDescription']=incident.MeterConditionDescription
        form.data['MeterSealInPlaceIndicator']=incident.MeterSealInPlaceIndicator
        form.data['JumperIndicator']=incident.JumperIndicator
        form.data['MeterBaseGoodConditionIndicator']=incident.MeterBaseGoodConditionIndicator
        form.data['LockGoodConditionIndicator']=incident.LockGoodConditionIndicator
        form.data['MapNumber']=incident.MapNumber
        form.data['AccountName']=incident.AccountName
        form.data['VehicleTagNumber']=incident.VehicleTagNumber
        form.data['VehicleDescription']=incident.VehicleDescription
        form.data['CutSealCharge']=incident.CutSealCharge
        form.data['TamperCharge']=incident.TamperCharge
        form.data['ServiceCharge']=incident.ServiceCharge
        form.data['VehiclesAtLocation']=incident.VehiclesAtLocation
        form.data['MiscellaneousCharge']=incident.MiscellaneousCharge
        form.data['ChargeDescription']=incident.ChargeDescription
        form.data['StolenCurrentCharge']=incident.StolenCurrentCharge
        form.data['TotalTheftCharges']=incident.TotalTheftCharges
        form.data['CaseNumber']=incident.CaseNumber
        form.data['County']=incident.County
        form.data['WarrantRequestedIndicator']=incident.WarrantRequestedIndicator
        form.data['PastDueBillAmount']=incident.PastDueBillAmount
        form.data['BadDebtAmount']=incident.BadDebtAmount
        form.data['HearingDateTime']=incident.HearingDateTime
        form.data['Decision']=incident.Decision
        form.data['OrderRestitutionIndicator']=incident.OrderRestitutionIndicator
        form.data['AccountName']=incident.AccountName
        form.data['AddressOne']=incident.AddressOne
        form.data['AddressTwo']=incident.AddressTwo
        form.data['AddressThree']=incident.AddressThree
        form.data['City']=incident.City
        form.data['State']=incident.State
        form.data['Zip']=incident.Zip
        form.data['HomePhone']=incident.HomePhone
        form.data['CellPhone']=incident.CellPhone
        form.data['OtherPhone']=incident.OtherPhone
        form.data['Fax']=incident.Fax
        form.data['Email']=incident.Email
        form.data['InitialFindingsIndicator']=incident.InitialFindingsIndicator
        form.data['InitialFindingsDateTime']=incident.InitialFindingsDateTime
        form.data['InitialFindingsDescription']=incident.InitialFindingsDescription
        form.data['InProgressIndicator']=incident.InProgressIndicator
        form.data['InProgressDateTime']=incident.InProgressDateTime
        form.data['InProgressDescription']=incident.InProgressDescription
        form.data['FilmIndicator']=incident.FilmIndicator
        form.data['FilmUploadedIndicator']=incident.FilmUploadedIndicator
        form.data['EvidenceBagNumber']=incident.EvidenceBagNumber
        if(incident.Point):
            form.data['Longitude']=str(incident.Point.transform(djangoproject.settings.COOPIPGPSSRID, clone=True).x)
            form.data['Latitude']=str(incident.Point.transform(djangoproject.settings.COOPIPGPSSRID, clone=True).y)
        else:
            form.data['Longitude']=''
            form.data['Latitude']=''
        form.data['UpdatePointManuallyIndicator']=False
        form.data['UpdatePointFromGISIndicator']=False
        form.data['UpdatePointFromGISField']=''
        form.data['LegalCodeTheftIndicator']=incident.LegalCodeTheftIndicator
        form.data['LegalCodeAlterIndicator']=incident.LegalCodeAlterIndicator
        form.data['LegalCodeCheatIndicator']=incident.LegalCodeCheatIndicator
        form.data['NewPaymentIndicator']=False
        form.data['NewPaymentAmount']=''
        form.data['NewPaymentDateTime']=''
        form.data['NewPaymentDescription']=''
        form.data['Description']=incident.Description
    else:
        form.data['SelectIncident']=-1
        form.data['Incidentid']=''
        form.data['InitialFindingsIndicator']=False
        form.data['InitialFindingsDescription']=''
        form.data['InitialFindingsDateTime']=''
        form.data['FilmIndicator']=False
        form.data['FilmUploadedIndicator']=False
        form.data['InProgressIndicator']=False
        form.data['InProgressDescription']=''
        form.data['InProgressDateTime']=''
        form.data['ClosedIndicator']=False
        form.data['ClosedDescription']=''
        form.data['ClosedDateTime']=''
        form.data['CutSealIndicator']=False
        form.data['MeterProperPositionIndicator']=False
        form.data['MeterConditionDescription']=''
        form.data['MeterSealInPlaceIndicator']=False
        form.data['JumperIndicator']=False
        form.data['MeterBaseGoodConditionIndicator']=False
        form.data['LockGoodConditionIndicator']=False
        form.data['MapNumber']=''
        form.data['NameOnAccount']=''
        form.data['VehicleTagNumber']=''
        form.data['VehicleDescription']=''
        form.data['CutSealCharge']=''
        form.data['TamperCharge']=''
        form.data['ServiceCharge']=''
        form.data['VehiclesAtLocation']=''
        form.data['MiscellaneousCharge']=''
        form.data['ChargeDescription']=''
        form.data['StolenCurrentCharge']=''
        form.data['TotalTheftCharges']=''
        form.data['CaseNumber']=''
        form.data['County']=''
        form.data['WarrantRequestedIndicator']=False
        form.data['PastDueBillAmount']=''
        form.data['BadDebtAmount']=''
        form.data['HearingDateTime']=''
        form.data['Decision']=''
        form.data['OrderRestitutionIndicator']=False
        form.data['AccountName']=''
        form.data['AddressOne']=''
        form.data['AddressTwo']=''
        form.data['AddressThree']=''
        form.data['City']=''
        form.data['State']=''
        form.data['Zip']=''
        form.data['HomePhone']=''
        form.data['CellPhone']=''
        form.data['OtherPhone']=''
        form.data['Fax']=''
        form.data['Email']=''
        form.data['InitialFindingsIndicator']=False
        form.data['InitialFindingsDateTime']=''
        form.data['InitialFindingsDescription']=''
        form.data['InProgressIndicator']=False
        form.data['InProgressDateTime']=''
        form.data['InProgressDescription']=''
        form.data['FilmIndicator']=False
        form.data['FilmUploadedIndicator']=False
        form.data['EvidenceBagNumber']=''
        form.data['Longitude']=''
        form.data['Latitude']=''
        form.data['UpdatePointManuallyIndicator']=False
        form.data['UpdatePointFromGISIndicator']=False
        form.data['UpdatePointFromGISField']=''
        form.data['LegalCodeTheftIndicator']=False
        form.data['LegalCodeAlterIndicator']=False
        form.data['LegalCodeCheatIndicator']=False
        form.data['NewPaymentIndicator']=False
        form.data['NewPaymentAmount']=''
        form.data['NewPaymentDateTime']=''
        form.data['NewPaymentDescription']=''
        form.data['Description']=''
    return form














def BuildAndProcessMeterInvestigationForm(request, ActiveButNotAuthorizedMeters, InvestigationMeters):
    ProcessMeterInvestigationFormRequest(request) #need to process directly from request, then get lists of meters, but do that after getting basics working
    FormDictionary=BuildMeterInvestigationForm(ActiveButNotAuthorizedMeters, InvestigationMeters)
    if request.method == 'POST':  #Setup the form so it can be processed/modified on this postback
        form=COOPIP_Misc.DynForm()
        form.setFields(FormDictionary)
        form.setData(request.POST)
        data={}
        for i in form.data.keys():  #Copy the Form Data to a dictionary then back to the form so it can be modified for the next screen view
            data[i] = form.data[i]
        form.data = data
    else:   #Otherwise, setup the Boolean values checked for processing to false
        form=COOPIP_Misc.DynForm()
        form.setFields(FormDictionary)
        form.data={}
    return form

def BuildMeterInvestigationForm(ActiveButNotAuthorizedMeters, InvestigationMeters):
    NumberOfMetersListedOnForm=len(ActiveButNotAuthorizedMeters) + len(InvestigationMeters)
    Dict={}
    Dict['PingMeterCommand'] = forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'12'}))
    for i in range(0, NumberOfMetersListedOnForm):
        Dict['UpdateIndicator' + str(i)]=forms.BooleanField(required=False)
        Dict['MeterNumber' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'7', 'READONLY':'True'}))
        Dict['LastSuccessfulPingDateTime' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10', 'READONLY':'True'}))
        Dict['TagNumber' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'4', 'READONLY':'True'}))
        Dict['LastPingResponseDateTime' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10', 'READONLY':'True'}))
        Dict['AppearedOnNotVerifiedListDateTime' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10', 'READONLY':'True'}))
        Dict['InvestigationIndicator' + str(i)]=forms.BooleanField()
        Dict['Description' + str(i)]=forms.CharField(required=False, widget=forms.Textarea(attrs={'rows':'2', 'cols':'50'}))
        Dict['InvestigationStartDateTime' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10', 'READONLY':'True'}))
        Dict['GISCircuitNumber' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'2', 'READONLY':'True'}))
        Dict['ServiceOrderDescription' + str(i)]=forms.CharField(required=False, widget=forms.Textarea(attrs={'rows':'2', 'cols': '20', 'READONLY':'True'}))
    return Dict

def ProcessMeterInvestigationFormRequest(request):
    #raise(Exception(str(request.POST['PingMeterCommand'])))
    Dict=request.POST
    try:
        PingMeterCommand=request.POST['PingMeterCommand']
        PingMeterCommandInteger=int(request.POST['PingMeterCommand'])
    except:
        PingMeterCommand=''
        PingMeterCommandInteger=0
    if(PingMeterCommand):
        Meters=[]
        if(djangoproject.models.ipbase.Meter.objects.filter(GISCircuitNumber=PingMeterCommand)):
            Meters=djangoproject.models.ipbase.Meter.objects.filter(GISCircuitNumber=PingMeterCommand)
        elif(djangoproject.models.ipbase.Meter.objects.filter(SerialNumber=PingMeterCommand)):
            TempMeter=djangoproject.models.ipbase.Meter.objects.filter(SerialNumber=PingMeterCommand)[0]
            Meters=[]
            Meters.append(TempMeter)
            NearbyMeters=TempMeter.GetNearbyMeters()
            for i in NearbyMeters:
                Meters.append(i)
        elif(PingMeterCommandInteger and (PingMeterCommandInteger % 100 == 0)):
            Meters = []
            TempMeters=djangoproject.models.ipbase.Meter.objects.all()
            #Need to add code to get all matching substation meters here.
        for meter in Meters:
            meter.Ping(ManualPingIndicator=True)
    i = 0
    while(True):
        if(not request.POST.has_key('Description' + str(i))):
            break
        if(request.POST.has_key('UpdateIndicator' + str(i))):
            UpdateIndicator= (request.POST['UpdateIndicator' + str(i)] == 'on')
        else:
            UpdateIndicator=False
        if(UpdateIndicator):
            MeterNumber = (request.POST['MeterNumber' + str(i)])
            if(request.POST.has_key('InvestigationIndicator' + str(i))):
                InvestigationIndicator= (request.POST['InvestigationIndicator' + str(i)] == 'on')
            else:
                InvestigationIndicator=False
            Description = (request.POST['Description' + str(i)])
            meter=djangoproject.models.ipbase.Meter.objects.filter(SerialNumber=MeterNumber)[0]
            meter.InvestigationIndicator=InvestigationIndicator
            meter.Description=Description
            meter.CalculateSymbology(False)
            meter.save()
        i = i + 1

def PopulateMeterInvestigationForm(form, ActiveButNotAuthorizedMeters, InvestigationMeters):
    NumberOfMetersListedOnForm=len(ActiveButNotAuthorizedMeters) + len(InvestigationMeters)
    Total = 0
    for i in range(0, len(ActiveButNotAuthorizedMeters)):
        form.data['UpdateIndicator' + str(Total)]=False
        form.data['MeterNumber' + str(Total)]=ActiveButNotAuthorizedMeters[i].SerialNumber
        form.data['LastSuccessfulPingDateTime' + str(Total)]=ActiveButNotAuthorizedMeters[i].LastSuccessfulPingDateTime
        form.data['TagNumber' + str(Total)]=ActiveButNotAuthorizedMeters[i].TagNumber
        form.data['LastPingResponseDateTime' + str(Total)]=ActiveButNotAuthorizedMeters[i].LastPingResponseDateTime
        form.data['AppearedOnNotVerifiedListDateTime' + str(Total)]=ActiveButNotAuthorizedMeters[i].AppearedOnNotVerifiedListDateTime
        form.data['InvestigationIndicator' + str(Total)]=ActiveButNotAuthorizedMeters[i].InvestigationIndicator
        form.data['Description' + str(Total)]=ActiveButNotAuthorizedMeters[i].Description
        form.data['InvestigationStartDateTime' + str(Total)]=ActiveButNotAuthorizedMeters[i].InvestigationStartDateTime
        form.data['GISCircuitNumber' + str(Total)]=ActiveButNotAuthorizedMeters[i].GISCircuitNumber
        Total=Total + 1
    for i in range(0, len(InvestigationMeters)):
        form.data['UpdateIndicator' + str(Total)]=False
        form.data['MeterNumber' + str(Total)]=InvestigationMeters[i].SerialNumber
        form.data['LastSuccessfulPingDateTime' + str(Total)]=InvestigationMeters[i].LastSuccessfulPingDateTime
        form.data['TagNumber' + str(Total)]=InvestigationMeters[i].TagNumber
        form.data['LastPingResponseDateTime' + str(Total)]=InvestigationMeters[i].LastPingResponseDateTime
        form.data['AppearedOnNotVerifiedListDateTime' + str(Total)]=InvestigationMeters[i].AppearedOnNotVerifiedListDateTime
        form.data['InvestigationIndicator' + str(Total)]=InvestigationMeters[i].InvestigationIndicator
        form.data['Description' + str(Total)]=InvestigationMeters[i].Description
        form.data['InvestigationStartDateTime' + str(Total)]=InvestigationMeters[i].InvestigationStartDateTime
        form.data['GISCircuitNumber' + str(Total)]=InvestigationMeters[i].GISCircuitNumber
        Total=Total + 1
    return form



def BuildSearchInMetersForm(SpecialBuildFormDataDict):
    Dict={}
    Dict['MeterString']=forms.CharField(required=False, widget=forms.Textarea(attrs={'rows':'10', 'cols':'80'}))
    Dict['UpdateIndicator']=forms.BooleanField(required=False)
    Dict['PriorityLevel']=forms.IntegerField(required=False, widget=forms.TextInput(attrs={'size':'6'}))
    Dict['ClearAMRQueueIndicator']=forms.BooleanField(required=False)
    Dict['DisplayUnlimitedIndicator']=forms.BooleanField(required=False)
    return Dict

def ProcessSearchInMetersForm(form, Username, request):
    UpdateIndicator=COOPIP_Form.FormGetBoolean(form, 'UpdateIndicator')
    PriorityLevel=COOPIP_Form.FormGetInteger(form, 'PriorityLevel')
    ClearAMRQueueIndicator=COOPIP_Form.FormGetBoolean(form, 'ClearAMRQueueIndicator')
    DisplayUnlimitedIndicator=COOPIP_Form.FormGetBoolean(form, 'DisplayUnlimitedIndicator')
    MeterString=COOPIP_Form.FormGetString(form, 'MeterString')
    Meters=MeterString.split('\n')
    if UpdateIndicator:
        for meter in Meters:
            meter=meter.replace('\r','')
            if ':' in meter:
                MeterAndSubstation=meter.split(':')
                SerialNumber=(MeterAndSubstation[0])
                PrioritySubstationIndicator=True
                PrioritySubstationName=MeterAndSubstation[1].lstrip(' ').rstrip(' ').upper()
                PrioritySubstation=djangoproject.models.amrcache.Substation.objects.filter(Name__iexact=PrioritySubstationName)[0]
            else:
                SerialNumber=(meter)
                PrioritySubstationIndicator=False
            try:
                Number=int(SerialNumber)
            except ValueError:
                continue
            newmeter=djangoproject.models.ipbase.MeterSearch()
            newmeter.SerialNumber=Number
            if PrioritySubstationIndicator:
                newmeter.PrioritySubstationIndicator=PrioritySubstationIndicator
                newmeter.PrioritySubstation=PrioritySubstation
            if PriorityLevel:
                newmeter.PriorityLevel=abs(PriorityLevel)
            else:
               newmeter.PriorityLevel=0
            newmeter.StartDateTime=datetime.datetime.now()
            newmeter.OutToAMRCount=0
            newmeter.save()
    elif ClearAMRQueueIndicator:
        OutCommands=AMR.Outcmd.objects.exclude(state=4)
        OutCommands.delete()
        InCommands=AMR.Incmd.objects.all()
        for i in InCommands:
            if (not AMR.Outcmd.objects.filter(msexid=i.msexid)):
                i.delete()
        import django
        django.db.connections['amr'].commit()
    return DisplayUnlimitedIndicator



def PopulateSearchInMetersForm(form):
    form.data['UpdateIndicator']=False
    form.data['PriorityLevel']=0
    form.data['ClearAMRQueueIndicator']=False
    form.data['DisplayUnlimitedIndicator']=False
    return form


def ProcessMeterBlinkFormRequest(request):
    #raise(Exception(str(request.POST)))
    if(not request.POST):
        return
    if(request.POST.has_key('UpdateIndicator')):
        UpdateIndicator=(request.POST['UpdateIndicator'] == 'on')
    else:
        return
    if(request.POST.has_key('SerialNumber')):
        SerialNumber=(request.POST['SerialNumber'])
    else:
        return
    try:
        meterBlink=djangoproject.models.ipbase.MeterBlink.objects.filter(Meter__SerialNumber=SerialNumber)[0]
    except:
        return
    if(request.POST.has_key('Description')):
        Description=(request.POST['Description'])
    else:
        return
    meterBlink.Description=Description
    meterBlink.save()

def PopulateMeterBlinkForm(form):
    form.data['UpdateIndicator']=False
    form.data['SerialNumber']=''
    form.data['ShowAllIndicator']=False
    form.data['Description']=''
    return form

def BuildMeterBlinkForm():
    Dict={}
    Dict['SerialNumber']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'12'}))
    Dict['Description']=forms.CharField(required=False, widget=forms.Textarea(attrs={'rows':'2', 'cols':'50'}))
    Dict['UpdateIndicator']=forms.BooleanField(required=False)
    Dict['ShowAllIndicator']=forms.BooleanField(required=False)
    return Dict

def BuildAndProcessMeterBlinkForm(request):
    ProcessMeterBlinkFormRequest(request)
    FormDictionary=BuildMeterBlinkForm()
    if request.method == 'POST':  #Setup the form so it can be processed/modified on this postback
        form=COOPIP_Misc.DynForm()
        form.setFields(FormDictionary)
        form.setData(request.POST)
        data={}
        for i in form.data.keys():  #Copy the Form Data to a dictionary then back to the form so it can be modified for the next screen view
            data[i] = form.data[i]
        form.data = data
    else:   #Otherwise, setup the Boolean values checked for processing to false
        form=COOPIP_Misc.DynForm()
        form.setFields(FormDictionary)
        form.data={}
    return form

def BuildMeterUsageVariationForm():
    Dict={}
    Dict['StartDate']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'12'}))
    Dict['EndDate']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'12'}))
    Dict['HourlyDataIndicator']=forms.BooleanField(required=False)
    return Dict

def ProcessMeterUsageVariationForm(form):
    StartDate=COOPIP_Form.StringToDate(COOPIPForm.FormGetString(form, 'StartDate'))
    EndDate=COOPIP_Form.StringToDate(COOPIPForm.FormGetString(form, 'EndDate'))
    HourlyDataIndicator=COOPIP_Form.FormGetBoolean(form, 'HourlyDateIndicator')


def BuildTruckMovementForm():
    Dict={}
    Dict['UpdateIndicator']=forms.BooleanField(required=False)
    Dict['ClearAllIndicator']=forms.BooleanField(required=False)
    Dict['TruckNumber']=forms.CharField(required=False)
    Dict['StartDateTime']=forms.DateTimeField(required=False)
    Dict['EndDateTime']=forms.DateTimeField(required=False)
    return Dict

def ProcessTruckMovementForm(form):
    UpdateIndicator=COOPIP_Form.FormGetBoolean(form, 'UpdateIndicator')
    ClearAllIndicator=COOPIP_Form.FormGetBoolean(form, 'ClearAllIndicator')
    TruckNumber=COOPIP_Form.FormGetString(form, 'TruckNumber')
    try:
        StartDateTime=form.data['StartDateTime']
    except:
        StartDateTime=''
    try:
        EndDateTime=form.data['EndDateTime']
    except:
        EndDateTime=''
    if UpdateIndicator:
        TruckLogs=djangoproject.models.ipbase.TruckLog.objects.filter(Number=TruckNumber).filter(CreateDateTime__gte=StartDateTime).filter(CreateDateTime__lte=EndDateTime)
        for i in TruckLogs:
            i.ShowOnMapIndicator=True
            i.save()
    elif ClearAllIndicator:
        TruckLogs=TruckLog.objects.filter(ShowOnMapIndicator=True)
        for i in TruckLogs:
            i.ShowOnMapIndicator=False
            i.save()

def PopulateTruckMovementForm(form):
    form.data['UpdateIndicator']=False
    form.data['ClearAllIndicator']=False
    form.data['TruckNumber']=''
    return form

def BuildDeleteFromAMRForm():
    Dict={}
    Dict['UpdateIndicator']=forms.BooleanField(required=False)
    Dict['ExecuteIndicator']=forms.BooleanField(required=False)
    Dict['SerialNumber']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'15'}))
    return Dict

def ProcessDeleteFromAMRForm(form):
    UpdateIndicator=COOPIP_Form.FormGetBoolean(form, 'UpdateIndicator')
    ExecuteIndicator=COOPIP_Form.FormGetBoolean(form, 'ExecuteIndicator')
    SerialNumber=COOPIP_Form.FormGetString(form, 'SerialNumber')
    if UpdateIndicator:
        return (SerialNumber, ExecuteIndicator)
    return (None, None)

def PopulateDeleteFromAMRForm(form):
    form.data['UpdateIndicator']=False
    form.data['ExecuteIndicator']=False
    return form





def BuildRevenueProtectionReportForm(SpecialBuildFormDataDict):
    Dict={}
    Dict['ImmediatelyGenerateReportIndicator']=forms.BooleanField(required=False)
    Dict['DeleteReportid']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'15'}))
    return Dict

def ProcessRevenueProtectionReportForm(form, Username):
    ImmediatelyGenerateReportIndicator=COOPIP_Form.FormGetBoolean(form, 'ImmediatelyGenerateReportIndicator')
    DeleteReportid=COOPIP_Form.FormGetString(form, 'DeleteReportid')
    
    if(ImmediatelyGenerateReportIndicator):
        djangoproject.models.revenueprotection.RevenueProtectionReport.GenerateReport(Username=Username)
    if(DeleteReportid):
        try:
             ReportToDelete=djangoproject.models.revenueprotection.RevenueProtectionReport.objects.filter(id=DeleteReportid)[0]
        except IndexError:
             ReportToDelete=None
        if(ReportToDelete):
            if(ReportToDelete.Username == Username):
                ReportToDelete.DeleteReport()

  
def PopulateRevenueProtectionReportForm(form):
    form.data['ImmediatelyGenerateReportIndicator']=False
    form.data['DeleteReportid'] = ''
    return form



def BuildVehicleHistoryForm():
    Dict={}
    Dict['Start']=forms.DateTimeField(required=False, widget=forms.TextInput(attrs={'size':'15'}))
    Dict['End']=forms.DateTimeField(required=False, widget=forms.TextInput(attrs={'size':'15'}))
    Dict['Label']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'15'}))
    Dict['Vehicles']=forms.CharField(required=False, widget=forms.Textarea(attrs={'rows': '6', 'cols': '20'}))
    return Dict

def ProcessVehicleHistoryForm(form):
    Dict={}
    RawStart = COOPIP_Form.FormGetString(form, 'Start')
    RawEnd = COOPIP_Form.FormGetString(form, 'End')
    Start = COOPIP_Form.StringDateTimeToDateTime(RawStart)
    End = COOPIP_Form.StringDateTimeToDateTime(RawEnd)
    Label = COOPIP_Form.FormGetString(form, 'Label')
    RawVehicles = COOPIP_Form.FormGetString(form, 'Vehicles')
    RawVehicles2 = RawVehicles.split('\n')
    VehicleNumberList=[]
    for i in RawVehicles2:
        try:
            test=int(i)
        except ValueError:
            continue
        VehicleNumberList.append(i.replace('\r', '').replace('\n',''))
    #raise Exception(str(Start) + ' ' + str(End))
    if not VehicleNumberList:
        return {}
    if not End:
        End = datetime.datetime.now()
    Logs = VehicleLog.objects.filter(VehicleNumber__in=VehicleNumberList).filter(CreateDateTime__gte=Start).filter(CreateDateTime__lte=End).order_by('VehicleNumber', 'CreateDateTime')
    #FilteredLogs = Logs.exclude(SymbologyTransmission__isnull=True)
    FilteredLogs=Logs
    for i in VehicleLog.objects.filter(SymbologyVisible='t'):
        i.SymbologyVisible=''
        i.save()
    for i in FilteredLogs:
        i.SymbologyVisible = 't'
        i.save()
    Dict={}
    Dict['Logs'] = FilteredLogs
    Dict['VehicleNumbers'] = VehicleNumberList
    return Dict

def PopulateVehicleHistoryForm(form):
    return form







def BuildRevenueProtectionReportNoteForm(SpecialBuildFormDataDict):
    Dict={}
    Dict['MeterNumber']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'20'}))
    Dict['RevenueProtectionReportNote']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'30'}))
    return Dict

def ProcessRevenueProtectionReportNoteForm(form, Username):
    MeterNumber=COOPIP_Form.FormGetString(form, 'MeterNumber')
    RevenueProtectionReportNote=COOPIP_Form.FormGetString(form, 'RevenueProtectionReportNote')
    meter=Meter.objects.filter(SerialNumber=MeterNumber)
    if(not meter):
        if(MeterNumber): 
            return 'No Matching Meter Found:  ' + str(MeterNumber)
        else:
            return ''
    meter[0].RevenueProtectionReportNote=RevenueProtectionReportNote
    meter[0].save()
    return 'Meter:  ' + str(meter[0].SerialNumber) + ' was updated.'


  
def PopulateRevenueProtectionReportNoteForm(form):
    form.data['MeterNumber']=''
    form.data['RevenueProtectionReportNote'] = ''
    return form











